//
//  DrivesViewController.m
//  carcareIOS
//
//  Created by ileo on 16/2/29.
//  Copyright © 2016年 baozun. All rights reserved.
//

#import "DrivesViewController.h"
#import "WaySummaryViewController.h"
#import "CalendarMgr.h"
#import "DrivesCell.h"
#import "MonthView.h"
#import "UIScrollView+LoadMore.h"
#import "DrivesMgr.h"

@interface DrivesViewController ()<HorizontalTableViewDataSourse,UIScrollViewDelegate,DrivesCellDelegate,LoadMoreControllerDelegate,MonthViewDelegate>

@property (nonatomic, assign) CGFloat lastOffsetX;

@property (nonatomic, strong) MonthView *monthView;

@end

@implementation DrivesViewController

#pragma  mark --- view live action

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.view addSubview:self.hTableView];
    
    self.navigationItem.title = @"行程";
    self.title = @"行程";
    
    [self.view addSubview:self.monthView];

    __weak __typeof(self) wself = self;
    DRIVERSMGR.LoadDayOK = ^(){
        [wself.hTableView reloadData];
    };
    [DRIVERSMGR startDayWithDate:[NSDate date]];
}

- (void)wakeFromBG{
    [self.hTableView reloadData];
}
#pragma mark - 将行程显示切换为今天
- (void)showTodayData
{
    NSDate * date = [NSDate date];
    self.monthView.choiceDate = date;
    [DRIVERSMGR startDayWithDate:date];
    [self.hTableView reloadData];
}

#pragma mark - horizontal datasource delegate

-(NSInteger)numberOfRowsWithHorizontalTableView:(HorizontalTableView *)horizontalTableView{
    return DRIVERSMGR.days.count;
}

-(CGFloat)horizontalTableView:(HorizontalTableView *)horizontalTableView widthForRow:(NSInteger)row{
    return __MAIN_WIDTH;
}

-(HorizontalTableViewCell *)horizontalTableView:(HorizontalTableView *)horizontalTableView cellForRow:(NSInteger)row{
    static NSString *cellID = @"drives";
    DrivesCell *cell = [horizontalTableView dequeueReusableCellWithIdentifier:cellID];
    if (!cell) {
        cell = [[DrivesCell alloc] initWithReuseIdentifier:cellID];
        cell.tableView.height = horizontalTableView.height;
    }
    NSDateComponents *dateComponents = [CalendarMgr componentsWithDate:DRIVERSMGR.days[row]];
    [DRIVERSMGR drivesWithDate:[NSString stringWithFormat:@"%zd-%02zd-%02zd",dateComponents.year,dateComponents.month,dateComponents.day] finish:^(DrivesModel *model) {
        cell.drivesModel = model;
        [cell updateTableViewContentInset];
        cell.noDrivesTips = (model ? @"今日无行程..." : @"正在加载..." );
        
    }];
    cell.delegate = self;

    return cell;
}

-(void)horizontalTableView:(HorizontalTableView *)horizontalTableView displayCells:(NSArray *)cells{
    if (cells.count > 0) {
        DrivesCell *cell = cells.firstObject;
        NSDate *date = DRIVERSMGR.days[cell.row];
        DRIVERSMGR.dayIndex = cell.row;
        self.monthView.choiceDate = date;
    }
}

#pragma mark - drivesCell delelgate

-(void)drivesDidScrollChangeTop:(CGFloat)top{
    if(self.hTableView.visibleCells.count > 0)
    {
        UITableView *tableV = ((DrivesCell *)self.hTableView.visibleCells[0]).tableView;
        if (top <= 0) {
            if (top <= [MonthView heightMin] - [MonthView heightMax]) {
                top = [MonthView heightMin] - [MonthView heightMax];
            }
            self.monthView.height = [MonthView heightMin] - top;
        }else{
            top = 0;
            self.monthView.height = [MonthView heightMin];
        }
        UIEdgeInsets edge = tableV.contentInset;
        edge.top = -top;
        tableV.contentInset = edge;
    }
}

-(void)drivesDidClickSelectModelIndex:(NSInteger)index{
    if(self.horizontalCellClick)self.horizontalCellClick(index);
}

-(void)drivesDidScrollEndTop:(CGFloat)top{
    if (top < 0 && top > [MonthView heightMin] - [MonthView heightMax]) {
        top = (top > ([MonthView heightMin] - [MonthView heightMax]) / 5 * 2) ? 0 : [MonthView heightMin] - [MonthView heightMax];
        UITableView *tableV = ((DrivesCell *)self.hTableView.visibleCells[0]).tableView;
        [tableV setContentOffset:CGPointMake(0, top) animated:YES];
    }else{
        self.hTableView.scrollEnabled = (top >= 0);
    }
}

#pragma mark - loadmore
-(void)loadMoreLeftFinish:(void (^)(CGFloat))finish withScrollView:(UIScrollView *)scrollView{
    __weak __typeof(self) wself = self;
    if ([self.monthView canLoadLastDay]) {
        [DRIVERSMGR loadLastDayFinish:^(NSInteger fromRow, NSInteger toRow) {
            [wself.hTableView reloadData];
            if (finish) {
                finish(wself.hTableView.width);
            }
        }];
    }else{
        if (finish) {
            finish(0);
        }
    }
}

-(void)loadMoreRightFinish:(void (^)())finish withScrollView:(UIScrollView *)scrollView{
    __weak __typeof(self) wself = self;
    if ([self.monthView canLoadNextDay]) {
        [DRIVERSMGR loadNextDayFinish:^(NSInteger fromRow, NSInteger toRow) {
            [wself.hTableView reloadData];
            if (finish) {
                finish();
            }
        }];
    }else{
        if (finish) {
            finish();
        }
    }
}

#pragma mark - scroll delegate
-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    if (self.lastOffsetX > scrollView.contentOffset.x) {
        [UmengMgr event:ICZ_Trip_Left];
    }else{
        [UmengMgr event:ICZ_Trip_Right];
    }
    self.lastOffsetX = scrollView.contentOffset.x;
}
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    [DRIVERSMGR loadPreloadDays];
}
-(void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView{
    [DRIVERSMGR loadPreloadDays];
}

#pragma mark - month delegate
-(BOOL)monthHadDrivesOnDate:(NSDateComponents *)dateComponents{
    NSString *str = [NSString stringWithFormat:@"%zd-%02zd-%02zd",dateComponents.year,dateComponents.month,dateComponents.day];
    return [DRIVERSMGR isDrivesInDate:str];
}

-(void)monthDidClickOnDate:(NSDateComponents *)dateComponents{
    
    NSDate *date = [[NSCalendar currentCalendar] dateFromComponents:dateComponents];
    UITableView *tableV = ((DrivesCell *)self.hTableView.visibleCells[0]).tableView;
    [self drivesDidScrollChangeTop:0];
    [self drivesDidScrollEndTop:0];
    [tableV setContentOffset:CGPointMake(0, 0) animated:YES];
    [DRIVERSMGR startDayWithDate:date];
    [self.hTableView reloadData];
    [DRIVERSMGR loadPreloadDays];

}

-(void)monthDidShowMonth:(NSDateComponents *)dateComponents{
    __weak __typeof(self) wself = self;
    [DRIVERSMGR calendarWayInfosWithYear:dateComponents.year month:dateComponents.month loadFirst:^{
        [wself.monthView reloadData];
    }];
}

-(void)monthDidClickOnFlexButton{
    if (self.monthView.height == [MonthView heightMax]) {
        UITableView *tableV = ((DrivesCell *)self.hTableView.visibleCells[0]).tableView;
        [tableV setContentOffset:CGPointMake(0, 0) animated:YES];
    }else if (self.monthView.height == [MonthView heightMin]) {
        UITableView *tableV = ((DrivesCell *)self.hTableView.visibleCells[0]).tableView;
        [tableV setContentOffset:CGPointMake(0, [MonthView heightMin] - [MonthView heightMax]) animated:YES];
    }
}

#pragma mark - set get

-(MonthView *)monthView{
    if (!_monthView) {
        
        NSDate *nextest = [NSDate date];
        NSDate *lastest = [CALENDARMGR dateWithStr:USERINFO.deviceBindingTime format:yyyy_MM_dd_HH_mm_ss];
        
        _monthView = [[MonthView alloc] initWithTop:0 choiceDate:[NSDate date] nextestDate:nextest lastestDate:lastest];
        _monthView.delegate = self;
    }
    return _monthView;
}

-(HorizontalTableView *)hTableView{
    if (!_hTableView) {
        _hTableView = [[HorizontalTableView alloc] initWithFrame:CGRectMake(0, [MonthView heightMin], __MAIN_WIDTH, __MAIN_HEIGHT_64_TABBAR - [MonthView heightMin])];
        _hTableView.dataSource = self;
        _hTableView.delegate = self;
        _hTableView.pagingEnabled = YES;
        _hTableView.showsHorizontalScrollIndicator = NO;
        [_hTableView setLoadMoreDelegate:self];
        [_hTableView setLoadMoreLeftView:[[LoadMoreView alloc] initWithFrame:CGRectMake(0, 0, 1, _hTableView.height)]];
        [_hTableView setLoadMoreRightView:[[LoadMoreView alloc] initWithFrame:CGRectMake(0, 0, 1, _hTableView.height)]];
    }
    return _hTableView;
}

#pragma  mark ---  Warn Memory

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
    // 将模型类中的数据进行删除操作
    
}

@end
